package com.syf.core.utils;

import cn.hutool.core.util.ClassUtil;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Comparator;

public class NewInstanceByClass {

    /**
     * 通过构造函数，动态反射构建实例对象.
     * 它解决某些类有多个构造函数，它会选最小参数数的构造函数初始化对象，值采用参数类型对应的默认值。
     */
    public static Object buildInstanceOnConstructor(Class<?> clazz) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
        Arrays.sort(declaredConstructors, Comparator.comparingInt(Constructor::getParameterCount));
        Constructor<?> selected = declaredConstructors[0];
        Object[] params = new Object[selected.getParameterCount()];
        Class<?>[] parameterTypes = selected.getParameterTypes();
        for (int i = 0; i < selected.getParameterCount(); i++) {
            params[i] = ClassUtil.getDefaultValue(parameterTypes[i]);
        }
        return selected.newInstance(params);
    }
}
